package com.example.idlefish.MyAccount.activity

import android.annotation.*
import android.content.*
import android.graphics.BitmapFactory
import android.os.*
import android.util.*
import android.widget.*
import androidx.activity.*
import com.example.idlefish.MyAccount.contract.*
import com.example.idlefish.MyAccount.pojo.*
import com.example.idlefish.PublicModule.*
import com.example.idlefish.databinding.*
import com.fasterxml.jackson.databind.*
import com.google.gson.*
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.*

@SuppressLint("SetTextI18n")
class LoginActivity : ComponentActivity() {
    private lateinit var binding: MyaccountLoginActivityBinding
    private val client = OkHttpClient()
    private val mapper = ObjectMapper()
    private var signInId = 0
    private val handler = Handler(Looper.getMainLooper())
    private val mediaType = "application/json;charset=utf-8".toMediaTypeOrNull()
    private val message = Message()


    private var userInfo: UserHomepageInfo? = null

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        binding = MyaccountLoginActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val prefs = getSharedPreferences("user_last", MODE_PRIVATE)
        if (prefs != null) {
            val lastUsername = prefs.getString("username", "")
            val lastUserPassword = prefs.getString("password", "")
            binding.username.setText("$lastUsername")
            binding.password.setText("$lastUserPassword")
    /*         if (lastUsername != null && lastUserPassword != null) {
                logIn(lastUsername, lastUserPassword)
            } */
        }
        
        binding.loading.hide()
        binding.loginButton.setOnClickListener {
            val username = binding.username.text.toString()
            val password = binding.password.text.toString()
            if (username.isEmpty() || password.isEmpty()) {
                Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            logIn(username, password)

        }

        binding.toRegister.setOnClickListener {
            registerLauncher.launch("跳转")
        }
    }







    /*
    * 登录
    * 测试数据
    * 邮箱: 123@qq.com
    * 密码: 123
    * */
    private fun logIn(account: String, password: String) {
        binding.loading.show()

        try {
            val request = Request.Builder().url(NetworkSettings.USER + "login?account=${account}&password=${password}")
                .get().build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    message.what = ResponseCode.REQUEST_FAILED
                    handler.post {
                        Utils.showMessage(applicationContext, message)
                    }
                    e.printStackTrace()
                }

                override fun onResponse(call: Call, response: Response) {
                    try {
                        if (response.isSuccessful && response.body != null) {
                            val gson = Gson()
                            val responseData = response.body?.string()
                            val jSon = gson.fromJson(responseData, UserHomepageInfoResult::class.java)
                            val info = jSon.data

                            Log.i("登录onResponse信息" , info.toString())
                            handler.post {

                                val editor = getSharedPreferences("user_last", MODE_PRIVATE).edit()
                                editor.putString("username", account)
                                editor.putString("password", password)
                                editor.apply()
                                if (info != null) {
                                    setAvatar(info.id.toString())
                                    UserConst.id = info.id
                                    UserConst.nickname = info.nickname ?:"小黄鱼"
                                    UserConst.avatarImage = info.avatar?.let {
                                        ApplicationConst.decodeBase64ToImage(applicationContext,
                                            it
                                        )
                                    }
                                    UserConst.intro = info.intro?:"这是一条小黄鱼的二手铺子"
                                    UserConst.sex = info.sex
                               /*      UserConst.followToIds = info.followToIds
                                    UserConst.fansIds = info.fansIds
                                    UserConst.collectionIds = info.collectionIds
                                    UserConst.browseHistoryIds = info.browseHistoryIds
                                    UserConst.myPostIds = info.myPostIds
                                    UserConst.mySoldIds = info.mySoldIds
                                    UserConst.myPurchasedIds = info.myPurchasedIds */
                                    info.avatar = ""
                                }

                                val intent = Intent()
                                intent.putExtra("userInfo", info as Serializable)
                                setResult(RESULT_OK, intent)
                                finish()
                            }
                            binding.loading.hide()

                        } else {
                            message.what = ResponseCode.SERVER_ERROR
                            Log.e("SERVER_ERROR", response.message)
                        }
                    } catch (e: Exception) {
                        message.what = ResponseCode.JSON_SERIALIZATION
                        handler.post {
                            // Utils.showMessage(applicationContext, message)
                        }
                        e.printStackTrace()
                    }
                }
            })
        } catch (e: Exception) {
            message.what = ResponseCode.JSON_SERIALIZATION
            Log.i("捕获异常", message.toString())
            e.printStackTrace()
        }
    }


    private fun setAvatar(id : String) {
        // 头像获取
        try {
            val request = Request.Builder().url(NetworkSettings.HTTP + "/avatar/avatarGet?id=${id}")
                .get().build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    e.printStackTrace()
                }

                override fun onResponse(call: Call, response: Response) {
                    try {
                        if (response.isSuccessful && response.body != null) {
                            UserConst.avatar = response.body?.string().toString()

                            try {
                                val decodedBytes = Base64.decode(UserConst.avatar, Base64.DEFAULT)
                                UserConst.avatarImage = BitmapFactory.decodeByteArray(
                                    decodedBytes,
                                    0,
                                    decodedBytes.size
                                )
                            } catch (e: IllegalArgumentException) {
                                e.printStackTrace()
                            }

                        } else {
                            Log.e("SERVER_ERROR", response.message)
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    // 启动器
    private val registerLauncher = registerForActivityResult(RegisterContract()) { result->
        if (result != null) {
            logIn(result.account, result.password)
        }
    }
}
